<template>
  <div class="initiate-events">
    <nav-header>
      <template slot="menuBefore">
        <li>
          <router-link to="/life/events/events-management" tag="a">赛事管理</router-link>
        </li>
        <li class="gap">&gt;</li>
      </template>
    </nav-header>
    <section class="initiate-container">
      <div class="form-box">
        <el-form ref="initiateForm" :model="initiateForm" :rules="rules" label-width="126px" label-position="left">
          <el-form-item label="赛事封面：">
            <cropperImage v-on:picture="getImgPath" style="width: 240px;height:135px;"></cropperImage>
          </el-form-item>
          <el-form-item label="赛事主题：" prop="name">
            <el-input v-model="initiateForm.name" placeholder="输入赛事主题，最多30个字符"></el-input>
          </el-form-item>
          <el-form-item label="赛事类型：">
            <el-select v-model="initiateForm.level_type" placeholder="请选择类型">
              <el-option label="校级赛事" value="1"></el-option>
              <el-option label="年级赛事" value="2"></el-option>
              <el-option label="班级赛事" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="赛事范围：" prop="org_id" v-if="initiateForm.level_type!='1'">
            <el-cascader v-model="initiateForm.org_id" :options="orgData" :props="orgDataProps" :show-all-levels="false" placeholder="请选择范围"></el-cascader>
          </el-form-item>
          <el-form-item label="赛事对象：" prop="role_id">
            <el-checkbox-group v-model="initiateForm.role_id">
            <!-- 班级、年级活动的对象：只针对学生、教师、家长 身份，因为这些身份以外的其他角色都无法加入到年级班级中-->
              <template v-if="initiateForm.level_type=='2'||initiateForm.level_type=='3'">
                <el-checkbox v-for="item of roleData.filter(item1=>item1.id=='4'||item1.id=='5'||item1.id=='6')" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
              </template>
              <!-- 年级活动的对象 -->
                <template v-else>
                <el-checkbox v-for="item of roleData" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
              </template>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="赛事时间：" prop="activityDate">
            <el-date-picker v-model="initiateForm.activityDate" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :editable="false" :time-arrow-control="true" :picker-options="pickerOptionsStart" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="赛事地点：" prop="place">
            <el-input v-model="initiateForm.place" maxlength="30" placeholder="输入赛事地点"></el-input>
          </el-form-item>
          <el-form-item label="赛事组织方：" prop="organizer">
            <el-input v-model="initiateForm.organizer" maxlength="30" placeholder="输入赛事组织方名称"></el-input>
          </el-form-item>
          <el-form-item label="赛事联系人：" prop="responsibler">
            <el-input v-model="initiateForm.responsibler" maxlength="30" placeholder="输入赛事联系人"></el-input>
          </el-form-item>
          <el-form-item label="赛事联系方式：" prop="telephone">
            <el-input v-model.number="initiateForm.telephone" placeholder="输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="在线报名：">
            <el-radio-group v-model="initiateForm.online">
              <el-radio label="1">允许</el-radio>
              <el-radio label="0">不允许</el-radio>
            </el-radio-group>
          </el-form-item>

            <template v-if="initiateForm.online=='1'">
            <el-form-item label="报名起止时间：" prop="registrationDate">
                <el-date-picker v-model="initiateForm.registrationDate" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :editable="false" :time-arrow-control="true" :picker-options="pickerOptionsStart" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="报名信息设置：" class="setting-item events-setting-item">
                <el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
                <el-tab-pane v-for="(item, index) in infoData" :key="item.id" :label="item.title" :name="item.id">
                    <el-form label-position="left" :model="item" :ref="'rules' + index">
                    <el-form-item prop="name" label-width="100px" label="项目名称：" :rules="[{validator: checkSpace,required: true}]">
                        <el-input v-model="item.name" placeholder="10个字符以内" maxlength="10"></el-input>
                    </el-form-item>
                    <el-form-item prop="quota" label-width="100px" label="项目名额：" :rules="[{ required: true, message: '项目名额不能为空'},{ type: 'number', message: '项目名额必须为数字值'}]">
                        <el-input v-model.number="item.quota" placeholder="输入数字，输入0则名额不限"></el-input>
                    </el-form-item>
                    <el-form-item label-width="100px" label="报名信息：">
                        <div class="activity-info-list">
                        <p>用户名、账号、学段>年级>班级、角色</p>
                        <div class="add-box" v-for="(item1,inx) of item.registration_information" :key="inx">
                            <el-input v-model="item1.name" maxlength="10" placeholder="填写用户需要登记的信息字段"></el-input>
                            <i class="el-icon-circle-plus" v-if="inx===0" @click="addRegister(item1,index,inx)"></i>
                            <i class="el-icon-remove" v-else @click.prevent="removeRegister(item1,index,inx)"></i>
                        </div>
                        </div>
                    </el-form-item>
                    </el-form>
                </el-tab-pane>
                </el-tabs>
            </el-form-item>
            </template>

          <el-form-item label="赛事介绍：" class="introduct-item">
            <div class="textarea-border">
              <el-input type="textarea" placeholder="请输入内容" v-model="initiateForm.profile" maxlength="2000" :autosize="{minRows: 16}" show-word-limit></el-input>
            </div>
          </el-form-item>
          <el-form-item class="submit-item">
            <el-button type="primary" class="submit-btn" @click="submitForm('initiateForm')">立即创建</el-button>
          </el-form-item>
        </el-form>
      </div>
    </section>
  </div>
</template>
<script>
import cropperImage from "../../common/cropper-image";
export default {
  components: {
    cropperImage
  },
  data() {
    return {
      pickerOptionsStart: {
        disabledDate: (time) => {
          return time.getTime() < parseInt(Date.now() - 8.64e7);
        }
      },
      initiateForm: {
        activityDate: [],//赛事开始-结束时间
        registrationDate: [],//报名开始-截止时间
        picture: "",//封面图片
        name: "",//赛事主题
        level_type: "1",//赛事类型 （1：校级；2：年级；3：班级；）
        org_id: [],//赛事范围，校级赛事隐藏此字段选项
        role_id: [],//赛事对象
        start_time: "",//赛事开始时间
        end_time: "",//赛事结束时间
        place: "",//赛事地点
        organizer: "",//赛事组织方
        responsibler: "",//赛事负责人
        telephone: "",//联系方式
        online: "0",//在线报名（0：不允许；1：允许；）
        registration_starttime: "",//报名开始时间
        registration_endtime: "",//报名结束时间
        project: [],//赛事项目名称
        registration_information: [],//报名信息设置
        profile: "",//赛事介绍
        create_id: this.$g.user_id,

      },
      rules: {
        name: [
          { required: true, message: '请输入赛事名称', trigger: 'blur' },
          { max: 30, message: '长度不超 30 个字符', trigger: 'blur' }
        ],
        org_id: [
          { type: "array", required: true, message: '请选择赛事区域', trigger: 'change' }
        ],
        role_id: [
          { type: 'array', required: true, message: '请至少选择一个赛事性质', trigger: 'change' }
        ],
        activityDate: [
          { required: true, message: '请选择日期' }
        ],
        registrationDate: [
          { required: true, message: '请选择日期' }
        ],
        place: [
          { required: true, message: '输入赛事地点', trigger: 'blur' }
        ],
        organizer: [
          { required: true, message: '输入赛事组织方名称', trigger: 'blur' }
        ],
        responsibler: [
          { required: true, message: '输入赛事联系人', trigger: 'blur' }
        ],
        telephone: [
          { type: 'number', required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],

      },
      roleData: [],//所有赛事对象数据
     // 年级（组织架构多级下拉框）：
      orgParam1: {
        data_type: "manage_tree",
        status: [1, 2],
        level: "<4" 
      },
          //班级级数组取到第四层
      orgParam2: {
        data_type: "manage_tree",
             status: [1],
        level: "<=4"
      },
      orgData: [],
      orgDataProps: {
        value: "id",
        label: "name",
        children: "children"
      },
      // 添加赛事项目：
      editableTabsValue: '1',
      infoData: [{
        title: '项目1',
        id: "1",
        name: "",
        quota: "",
        registration_information: [{//报名信息设置
          id: 0,
          name: "",
          value:""
        }],
      }],
      tabIndex: 1,
    };
  },
  created() {
    this.getRoleData();
  },
  mounted() {

  },
  watch: {
    "initiateForm.activityDate"(newVal, oldVal) {
      if (newVal != oldVal) {
        this.initiateForm.start_time = newVal[0];
        this.initiateForm.end_time = newVal[1];
      }
    },
    "initiateForm.registrationDate"(newVal, oldVal) {
      if (newVal != oldVal) {
        this.initiateForm.registration_starttime = newVal[0];
        this.initiateForm.registration_endtime = newVal[1];
      }
    },
    "initiateForm.level_type"(newVal, oldVal) {
      //根据活动类型，获取活动范围的数据(选择校级活动时，不显示活动范围这一行选项)
      if (newVal == "2") {
        // 年级活动类型
        this.getAreaData("2",this.orgParam1);
      } else if (newVal == "3") {
        //班级活动类型
        this.getAreaData("3",this.orgParam2);
      }
    },
  },
  computed: {

  },
  methods: {
    // 赛事封面上传点击事件
    getImgPath(picture) {
      this.initiateForm.picture = picture;
    },
    // 获取范围type年级2 班级3；orgParam是获取年级、班级传不同的参数
    getAreaData(type,orgParam) {
       let success = data => {
          // 后台返回的多层嵌套数据，最后一层的children键值对值为[]时，element的cascader级联选择器在页面显示最后一级为空白，所以要把json数据最里面的一层的children键值对的值设为undefined
          this.orgData = this.getTreeData(data.data);//只获取到年级的数据
      };
      this.$ajax.get("api/org/org", {
        params: orgParam,
        func: { success: success }
      });
    },
    // 递归遍历将多层嵌套数组里最里的空children数组的值改为undefined
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 获取角色列表
    getRoleData() {
      let success = data => {
        this.roleData = data.data;
      };
      this.$ajax.get("api/role/get_all", {
        params: {},
        func: { success: success }
      });
    },
    /**
     * 添加报名信息
     */
    addRegister(item, index, inx) {
      let length = this.infoData[index].registration_information.length;
      if (length >= 6) {
        this.$message.warning("您已添加6个字段，不能再添加了~");
        return;
      }
      this.infoData[index].registration_information.push({
        id: length,
        name: "",
        value: ""
      });
    },
    /**
    * 移除报名信息
    */
    removeRegister(item, index, inx) {
      var _index = this.infoData[index].registration_information.indexOf(item);
      if (_index !== -1) {
        this.infoData[index].registration_information.splice(_index, 1);
      }
    },
    // 提交点击事件
    submitForm(formName) {
      let infoData = this.infoData;
      infoData.forEach((item,inx)=>{
        let obj1={};
        let obj2={};
        obj1.id=item.id;
        obj1.name=item.name;
        obj1.quota=item.quota;
        obj2.id=item.id;
        obj2.info=item.registration_information;
        this.initiateForm.project.push(obj1);
        this.initiateForm.registration_information.push(obj2);
      });
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formValid("verify");
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    // 表单验证
    formValid(flag) {
      let forms = this.$refs;
      let endValids = [];
      for (let form in forms) {
        if (form.indexOf("rules") > -1) {
          if (flag === "verify") {
            forms[form][0].validate(valid => {
              endValids.push(valid);
            });
          }
          if (flag === "reset") {
            forms[form][0].resetFields();
          }
        }
      }
      if (endValids.indexOf(false) < 0) {
        this.saveData();
      }
    },
    // 验证通过后，数据提交
    saveData() {
      let params = deep_clone(this.initiateForm);
      // console.log(params)
      // 校级赛事类型的时候，赛事范围参数值为1，其他类型，只需要传赛事类型最末的一层的值
      if (this.initiateForm.level_type == "1") {
        params.org_id = "1";
      } else {
        let id = this.initiateForm.org_id.pop();
        params.org_id = id;
      }
      const success = (res => {
        this.$message.success(res.msg);
        this.resetForm();
      })
      const fail = (res => {
        this.$message.error(res.msg);
      })
      this.$ajax.post("api/competition/match", params, { func: { success: success, fail: fail } });
    },
    /**
   * 返回上一级
   */
    resetForm() {
      this.$router.go(-1);
    },
    // 报名信息新增或移除
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        let newTabName = ++this.tabIndex + '';
        this.infoData.push({
          title: `项目${newTabName}`,
          id: newTabName,//模板el-tabs上面是遍历key是用name，所有这里每次新建添加的时候，name都要确保唯一性
          name: "",
          quota: "",
          registration_information: [{//报名信息设置
            id: 0,
            name: "",
            value: ""
          }],
        });
        this.editableTabsValue = newTabName;
      }
      if (action === 'remove') {
        let tabs = this.infoData;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.id === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.id;
              }
            }
          });
        }

        this.editableTabsValue = activeName;
        this.infoData = tabs.filter(tab => tab.id !== targetName);
      }
    },
    // 自定义表单验证
    checkSpace(rule, value, callback) {
      let trim = value.trim();
      if (!trim) {
        callback(new Error("请输入项目名称"));
      } else {
        callback();
      }
    },
  },
};
</script>
<style lang="scss">
.initiate-container {
  .form-box {
    .el-form {
      display: inline-block;
      width: 626px;
      .el-form-item__label {
        width: 126px;
      }
    }
    .el-form-item {
      margin-bottom: 30px;
    }
    .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
    .el-form-item__content {
      text-align: left;
    }
    .el-select,
    .el-cascader,
    .el-date-editor--datetimerange.el-input__inner {
      width: 100%;
    }
    .introduct-item {
      .textarea-border {
        padding-top: 72px;
        position: relative;
        &::after {
          content: "";
          position: absolute;
          top: 36px;
          left: 0;
          box-sizing: border-box;
          display: inline-block;
          width: 100%;
          height: 36px;
          border: 1px solid #dcdfe6;
          border-bottom: none;
          border-radius: 4px 4px 0 0;
          background-image: linear-gradient(-180deg, #ffffff 0%, #fafafa 100%);
        }
      }
      .el-textarea__inner {
        border-radius: 0 0 4px 4px;
      }
      label {
        display: block;
        width: 100% !important;
      }
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
    .setting-item {
      p {
        margin: 0;
      }
      .add-box {
        padding: 15px 0;
        position: relative;
        i {
          font-size: 24px;
          position: absolute;
          right: -30px;
          bottom: 18px;
          cursor: pointer;
        }
      }
      .el-icon-remove {
        color: #d33c69;
      }
      .el-icon-circle-plus {
        color: #348efc;
      }
    }
    .submit-item {
      .el-form-item__content {
        margin-left: 0 !important;
        text-align: center;
      }
    }
    .submit-btn {
      width: 260px;
    }
  }
}
.events-setting-item {
  .el-form-item__content {
    margin-left: 0px !important;
  }
  .el-tabs {
    margin-top: 40px;
  }
  .add-box {
    width: 92%;
  }
}
</style>